package com.lzs.common.utils;

import com.lzs.common.enums.ResultCodeEnum;
import com.lzs.common.exception.LzsBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.Optional;

@Slf4j
public class SecurityUserUtils {
    public static SecurityUser getSecurityUser(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(Objects.isNull(principal)){
            throw new LzsBusinessException(ResultCodeEnum.UNAUTHORIZED_ERROR,"请登陆");
        }
        if (!(principal instanceof SecurityUser)){
            log.warn("获取的用户类型错误");
            throw new LzsBusinessException(ResultCodeEnum.UNAUTHORIZED_ERROR,"请登陆");
        }
        SecurityUser securityUser = (SecurityUser) principal;
        return securityUser;
    }
}
